package com.heima.comment.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.article.IArticleClient;
import com.heima.apis.user.IUserClient;
import com.heima.comment.pojos.ApComment;
import com.heima.comment.pojos.ApCommentLike;
import com.heima.comment.pojos.CommentVo;
import com.heima.comment.service.ApCommentService;
import com.heima.common.constants.HotArticleConstants;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.comment.dtos.CommentDto;
import com.heima.model.comment.dtos.CommentLikeDto;
import com.heima.model.comment.dtos.CommentSaveDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class ApCommentServiceImpl implements ApCommentService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IUserClient userClient;
    @Autowired
    private IArticleClient articleClient;
    @Autowired
    KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 保存评论
     *
     * @return
     */
    @Override
    public ResponseResult save(CommentSaveDto dto) {
        //1.检查参数
        if (dto == null || StringUtils.isBlank(dto.getContent()) || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.校验文章是否可以评论
        if (!checkParam(dto.getArticleId())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "改文章评论权限已关闭");
        }
        if (dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论内容不得超过140字");
        }
        //3.判断是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //4.保存评论
        ApUser apUser = userClient.findUserById(user.getId());
        ApComment apComment = new ApComment();
        apComment.setAuthorId(apUser.getId());
        apComment.setAuthorName(apUser.getName());
        apComment.setContent(dto.getContent());
        apComment.setImage(apUser.getImage());
        apComment.setFlag((short) 0);
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setType((short) 0);
        apComment.setEntryId(dto.getArticleId());
        apComment.setCreatedTime(new Date());
        mongoTemplate.save(apComment);
        //消息聚合发送--增加评论数量--计算热点文章
        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setArticleId(dto.getArticleId());
        mess.setType(UpdateArticleMess.UpdateArticleType.COMMENT);
        mess.setAdd(1);
        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(mess));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 加载评论--分页
     *  bug：新增时会出现两条相同的数据--不过两条数据其实是一条数据
     * @param dto
     * @return
     */
    public ResponseResult load(CommentDto dto) {
        //1.检查参数
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }   //默认10条数据
        int size = 10;
        //2.加载数据
        Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId()).and("createdTime").lt(dto.getMinDate()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                .limit(size);   //限制10个
        List<ApComment> list = mongoTemplate.find(query, ApComment.class);
        //3.返回数据封装
        //用户未登录---看不到点赞数
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.okResult(list);
        }
        //用户登录
        //查询当前作品中哪些被点赞了
        //这10条评论的 id
        List<String> idList = list.stream().map(x -> x.getId()).collect(Collectors.toList());
        //查询commentLikes表中哪个评论是该用户点过的赞
        Query query1 = Query.query(Criteria.where("commentId").in(idList).and("authorId").is(user.getId()));
        List<ApCommentLike> apCommentLikes = mongoTemplate.find(query1, ApCommentLike.class);
        if (apCommentLikes.size() == 0) {
            //未查询到该用户的相关点赞--直接返回10条评论--list
            return ResponseResult.okResult(list);
        }
        //若查询到的话--封装返回的数据--加入operation
//        List<CommentVo> resultList = new ArrayList<>();
//        for (ApComment apComment : list) {
//            CommentVo vo = new CommentVo();
//            BeanUtils.copyProperties(apComment, vo);
//            for (ApCommentLike apCommentLike : apCommentLikes) {
//                if (apCommentLike.getCommentId().equals(apComment.getId())) {
//                    vo.setOperation((short) 0);
//                }
//                resultList.add(vo);
//            }
//        }

        List<CommentVo> resultList = new ArrayList<>();
        list.forEach(x -> {
            CommentVo vo = new CommentVo();
            BeanUtils.copyProperties(x, vo);
            for (ApCommentLike apCommentLike : apCommentLikes) {
                if (x.getId().equals(apCommentLike.getCommentId())) {
                    vo.setOperation((short) 0);
                    break;
                }
            }
            resultList.add(vo);
        });
        return ResponseResult.okResult(resultList);
    }

    /**
     * 点赞
     * @param dto
     * @return
     */
    public ResponseResult like(CommentLikeDto dto) {
        //1.检查参数
        if (dto == null || dto.getCommentId() == null || dto.getOperation() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        //3.点赞
        if (apComment != null && dto.getOperation() == 0) {
            //更新评论点赞数
            apComment.setLikes(apComment.getLikes() + 1);
            mongoTemplate.save(apComment);
            //保存点赞数据
            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setCommentId(apComment.getId());
            apCommentLike.setAuthorId(user.getId());
            mongoTemplate.save(apCommentLike);
        } else {     //取消点赞
            //更新评论点赞数
            if (apComment.getLikes()-1<0){
                apComment.setLikes(0);
            }
            apComment.setLikes(apComment.getLikes()-1);
            mongoTemplate.save(apComment);
            //删除点赞数据
            Query query=Query.query(Criteria.where("commentId").is(apComment.getId()).and("authorId").is(user.getId()));
            mongoTemplate.remove(query,ApCommentLike.class);
        }
        //封装返回数据--需返回该数据的点赞数量
        Map<String,Object> map=new HashMap<>();
        map.put("likes",apComment.getLikes());
        return ResponseResult.okResult(map);
        }

    /**
     * 校验文章是否可以评论
     *
     * @param articleId
     * @return
     */
    private boolean checkParam(Long articleId) {
        //是否可以评论
        ResponseResult configResult = articleClient.findArticleConfigByArticleId(articleId);
        if (!configResult.getCode().equals(200) || configResult.getData() == null) {
            return false;
        }

        ApArticleConfig apArticleConfig = JSON.parseObject(JSON.toJSONString(configResult.getData()), ApArticleConfig.class);
        if (apArticleConfig == null || !apArticleConfig.getIsComment()) {
            return false;
        }

        return true;
    }

}
